﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;

namespace Expect.Core.Errors
{
    /// <summary>
    /// Helper for exceptions
    /// </summary>
    public static class ExceptionHelper
    {
        /*private static Action<Exception> _preserveInternalException;

        static ExceptionHelper()
        {
            MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
            _preserveInternalException = (Action<Exception>)Delegate.CreateDelegate(typeof(Action<Exception>), preserveStackTrace);
        }*/

        /// <summary>
        /// Set the stack trace of the exception to the current stack trace. It's usefull to rewrap exceptions such as targetinvocationexception
        /// </summary>
        /// <param name="e"></param>
        public static void PreserveStackTrace(this Exception e)
        {
            var ctx = new StreamingContext(StreamingContextStates.CrossAppDomain);
            var mgr = new ObjectManager(null, ctx);
            var si = new SerializationInfo(e.GetType(), new FormatterConverter());

            e.GetObjectData(si, ctx);
            mgr.RegisterObject(e, 1, si); // prepare for SetObjectData 
            mgr.DoFixups(); // ObjectManager calls SetObjectData 
        }
    }

}
